package com.cropdoctor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.internal.OSSUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cropdoctor.common.CustomException;
import com.cropdoctor.common.Result;
import com.cropdoctor.mapper.HistoryImgClsMapper;
import com.cropdoctor.model.dto.*;
import com.cropdoctor.model.po.HistoryImgClsPo;
import com.cropdoctor.service.ImgIdfClassificationService;
import com.cropdoctor.util.AliOssUtil;
import com.cropdoctor.util.ContextGet;
import com.cropdoctor.util.HttpUtils;
import com.cropdoctor.util.Img2Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

//识别果蔬类型
@Service
public class ImgIdfClassificationServiceImpl implements ImgIdfClassificationService {

    @Value("${class.host}")
    String host;
    @Value("${class.path}")
    String path;
    @Value("${aliyuncommon.method}")
    String method;
    @Value("${aliyuncommon.appcode}")
    String appcode;

    @Autowired
    HistoryImgClsMapper historyImgClsMapper;

    @Autowired
    AliOssUtil ossUtil;

    @Override
    @Transactional
    public Result<List<ImgClassificationDto>> ImgIdf(MultipartFile img)  {
        String filename = img.getOriginalFilename();
        File tempFile = null;
        byte[] bytes = null;
        String absolutePath = "";
        String tempName = "";
        try {
            tempFile = File.createTempFile("oss", ".temp");
            absolutePath = tempFile.getAbsolutePath();//临时文件路径
            bytes = img.getBytes();
            img.transferTo(tempFile);
            tempName = tempFile.getName();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("创建临时文件失败!");
        }

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        try {
            bodys.put("base64", Img2Base64.jpgToBase(absolutePath));
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("图片转base64失败!");
        }finally{
            if(tempFile != null) tempFile.delete();//程序退出时删除临时文件
        }

        List<ImgClassificationDto> imgClassificationDtos = null;
        String url = null;
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            String json = EntityUtils.toString(response.getEntity(), "utf-8");

            Map map = JSON.parseObject(json, Map.class);
            Map dataMap = (Map<String,String>)map.get("data");
            JSONArray results = (JSONArray)dataMap.get("results");
            imgClassificationDtos = results.toJavaList(ImgClassificationDto.class);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取解析结果失败！");
        }
        //获取原始的文件名
        String originalFilename = tempName;
        //在oss中存储名字就是UUID + 文件的后缀名
        String objectName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        url = ossUtil.upload(bytes, "history/"+"cls/"+objectName);

        ArrayList<String> scores = new ArrayList<>();
        ArrayList<String> names = new ArrayList<>();

        imgClassificationDtos.forEach(item ->{
            names.add(item.getName());
            scores.add(item.getScore());
        });

        String clsJson = JSON.toJSONString(names);
        String scoresJson = JSON.toJSONString(scores);
        HistoryImgClsPo historyImgClsPo = new HistoryImgClsPo();
        historyImgClsPo.setName(clsJson);
        historyImgClsPo.setScore(scoresJson);
        historyImgClsPo.setUserId(ContextGet.getUserId());
        historyImgClsPo.setUrl(url);

        int result = historyImgClsMapper.insert(historyImgClsPo);
        if(result <= 0){
            throw new CustomException("添加历史记录失败!");
        }

        return Result.success(imgClassificationDtos);
    }

    @Override
    public Result<List<HistoryImgClsDto>> getHistory(Long userId, LocalDateTime dateTime,Long id) {
        LambdaQueryWrapper<HistoryImgClsPo> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(HistoryImgClsPo::getUserId,userId)
                .le(dateTime != null,HistoryImgClsPo::getCreateDateTime,dateTime)
                .eq(id != 0,HistoryImgClsPo::getIdH,id)
                .orderByDesc(dateTime != null,HistoryImgClsPo::getCreateDateTime);

        List<HistoryImgClsPo> HistoryImgClsPos = historyImgClsMapper.selectList(queryWrapper);
        List<HistoryImgClsDto> historyImgClsDtos = new ArrayList<>();
        if(HistoryImgClsPos.size() != 0){
            HistoryImgClsPos.forEach(item->{
                HistoryImgClsDto historyImgClsDto = new HistoryImgClsDto();
                List<String> scores = JSON.parseArray(item.getScore(), String.class);
                List<String> names = JSON.parseArray(item.getName(), String.class);
                historyImgClsDto.setIdH(item.getIdH());
                historyImgClsDto.setScores(scores);
                historyImgClsDto.setNames(names);
                historyImgClsDto.setUrl(item.getUrl());
                historyImgClsDto.setCreateDateTime(item.getCreateDateTime());

                historyImgClsDtos.add(historyImgClsDto);
            });
        }else{
            throw new CustomException("该用户的历史数据为空!");
        }
        return Result.success(historyImgClsDtos);
    }
}

